package william.tree;

/**
 * @author ZhangShenao
 * @date 2024/3/19
 * @description <a href="https://leetcode.cn/problems/same-tree/description/">...</a>
 */
public class Leetcode100_相同的树 {
    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 采用递归算法
     * 首先校验当前的两个根节点是否相同,然后递归校验左、右子树是否也相同
     * <p>
     * 时间复杂度O(N) 两棵树各遍历一次
     * 空间复杂度O(logN) 递归栈深度=树高度
     */
    public boolean isSameTree(TreeNode p, TreeNode q) {
        //递归终止条件
        if (p == null && q == null) {
            return true;
        }


        if (p == null || q == null) {    //两棵树结构不同
            return false;
        }

        if (p.val != q.val) {    //两棵树节点值不同
            return false;
        }

        //递归判断左、右子树
        return (isSameTree(p.left, q.left) && isSameTree(p.right, q.right));
    }

}
